
class Banner {
  constructor (ele) {
    this.ele = document.querySelector(ele)
    this.imgBox = this.ele.querySelector('.imgBox')
    this.index = 0
    this.timer = 0
    this.init()
  }

  init () {
    this.autoPlay()
    this.overOut()
    this.changePage()
  }

  changeOne (type) {
    this.imgBox.children[this.index].classList.remove('active')

    if (type === true) {
      this.index++
    } else if (type === false) {
      this.index--
    } else {
      this.index = type
    }

    if (this.index >= this.imgBox.children.length) this.index = 0
    if (this.index < 0) this.index = this.imgBox.children.length - 1

    this.imgBox.children[this.index].classList.add('active')
  }

  autoPlay () {
    this.timer = setInterval(() => {
      this.changeOne(true)
    }, 2000)
  }

  overOut () {
    this.ele.addEventListener('mouseenter', (e) => {

      e.stopPropagation()

      clearInterval(this.timer)
    })
    this.ele.addEventListener('mouseleave', (e) => {

      e.stopPropagation()
      
      this.autoPlay()
    })
  }

  changePage () {
    document.addEventListener('visibilitychange', () => {
      const state = document.visibilityState

      if (state === 'hidden') clearInterval(this.timer)
      if (state === 'visible') this.autoPlay()
    })
  }
}
